import { Router } from 'express';
import { db } from '../utils/db.js';
import { requireAuth } from '../utils/auth.js';

const router = Router();

router.get('/', requireAuth, (req, res) => {
  const { tender_id } = req.query;
  let messages = [];
  if (tender_id) {
    messages = db
      .prepare(
        `SELECT m.*, u.username
         FROM messages m JOIN users u ON u.id = m.author_id
         WHERE m.tender_id = ?
         ORDER BY m.created_at DESC`
      )
      .all(tender_id);
  } else {
    messages = db
      .prepare(
        `SELECT m.*, u.username
         FROM messages m JOIN users u ON u.id = m.author_id
         ORDER BY m.created_at DESC`
      )
      .all();
  }
  if (req.accepts('html')) {
    return res.render('messages', { messages, tenderId: tender_id || null, title: '留言板' });
  }
  return res.json(messages);
});

router.post('/', requireAuth, (req, res) => {
  const { content, tender_id } = req.body;
  if (!content || !content.trim()) {
    return res.status(400).render('error', { message: '留言内容不能为空' });
  }
  db.prepare('INSERT INTO messages (author_id, tender_id, content) VALUES (?,?,?)').run(
    req.session.user.id,
    tender_id || null,
    content.trim()
  );
  if (tender_id) {
    return res.redirect(`/messages?tender_id=${tender_id}`);
  }
  return res.redirect('/messages');
});

export default router;


